package com.sisgh.jefdv1.core.jdbc.connection.factory.impl;

import com.sisgh.jefdv1.core.jdbc.connection.factory.ConnectionFactory;
import com.sisgh.jefdv1.core.jdbc.connection.properties.ConnectionProperties;
import com.sisgh.jefdv1.core.jdbc.db.Database;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * mysql 专用
 */
@Slf4j
public class MySQLConnectionFactory implements ConnectionFactory {

    private static final Database DB = Database.MYSQL;

    /**
     * 加载驱动
     */
    public MySQLConnectionFactory() {
        log.info("加载 mysql 驱动");

        try {
            Class.forName(DB.getDriverName());
        } catch (ClassNotFoundException e) {
            log.error("mysql 驱动加载失败，请检查相关依赖");
            log.error(e.getMessage(), e);

            throw new RuntimeException(e);
        }
    }


    private Connection getConnection(String url) throws SQLException {
        log.info("通过 url 加载 mysql Connection");

        return DriverManager.getConnection(url);
    }

    private Connection getConnection(String url, Properties properties) throws SQLException {
        log.info("通过 url、properties 加载 mysql Connection");

        return DriverManager.getConnection(url, properties);
    }

    private Connection getConnection(String url, String user, String password) throws SQLException {
        log.info("通过 url、user、password 加载 mysql Connection");

        return DriverManager.getConnection(url, user, password);
    }

    @Override
    public Connection getConnection(ConnectionProperties cps) throws SQLException {
        log.info("获取 mysql Connection 实例");

        int validate = cps.validate(DB);

        return switch (validate) {
            case ConnectionProperties.URL_HAS_USER_PWD ->
                    getConnection(cps.getUrl());
            case ConnectionProperties.URL_NOT_USER_PWD ->
                    getConnection(cps.getUrl(), cps.getUsername(), cps.getPassword());
            case ConnectionProperties.PROPERTIES_HAS_USER_PWD ->
                    getConnection(cps.getUrl(), cps.getProperties());
            default -> {
                    log.error("非法的 url");
                    throw new SQLException("invalid url");
                }
        };
    }

    @Override
    public String getDBType() {
        return "MySQL";
    }
}
